package com.wgly.question.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wgly.question.bean.Msg;
import com.wgly.question.service.WritesSqlService;
import com.wgly.question.utils.PropertieUtil;
@Controller
public class UploadController {
	@Autowired
	WritesSqlService writesSqlService;
	  //实现文件上传
		@PostMapping("/upload")
		@ResponseBody
	     public Msg Upload(HttpServletRequest request,@RequestParam(value="files",required=false) MultipartFile multipartFile) throws Exception {
			 String file=DownloadExcel(multipartFile);
			  writesSqlService.WritesSqlService(file);
			  return Msg.success();
		}
		//将上传的excel保存在本地
		private String DownloadExcel(MultipartFile multipartFile) throws IOException {
			StringBuilder stringBuilder = new StringBuilder();
			String realpath="";
			String name="";
			if(multipartFile!=null) {
				long size = multipartFile.getSize();
				if(size>5242880) {
					throw new NullPointerException();
				}
			 name= multipartFile.getOriginalFilename();
			 String substring = name.substring(name.lastIndexOf(".")+1, name.length());
			 String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			 String filepath=PropertieUtil.readProperty("url")+"UploadExcel"+File.separator;
			 File file = new File(filepath);
			 if(!file.exists()) {
				 file.mkdirs();
			 }
			 multipartFile.transferTo(new File(file +"\\"+fileName+"."+substring));
		     realpath=file+"\\"+fileName+"."+substring;
		     stringBuilder.append(realpath);		     
		}
		 System.out.println(stringBuilder.toString());
         return stringBuilder.toString();
		}
}
